package com.example.demo.sensitive.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.sensitive.dto.request.DatabaseConfigRequest;
import com.example.demo.sensitive.dto.response.DatabaseConfigResponse;
import com.example.demo.sensitive.entity.DatabaseConfig;
import com.example.demo.sensitive.mapper.DatabaseConfigMapper;
import com.example.demo.sensitive.service.DatabaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName DatabaseServiceImpl
 * @Description 数据库服务实现类
 * @Author System
 * @Date 2025/9/19
 **/
@Service
public class DatabaseServiceImpl extends ServiceImpl<DatabaseConfigMapper, DatabaseConfig> implements DatabaseService {

    @Autowired
    private DatabaseQueryService databaseQueryService;

    @Override
    public Page<DatabaseConfigResponse> getPageList(int current, int size, Integer status, String dbType, String keyword) {
        Page<DatabaseConfig> page = new Page<>(current, size);
        Page<DatabaseConfig> result = page(page);
        
        Page<DatabaseConfigResponse> responsePage = new Page<>(current, size);
        responsePage.setTotal(result.getTotal());
        responsePage.setSize(result.getSize());
        responsePage.setCurrent(result.getCurrent());
        
        // 转换实体到响应对象
        List<DatabaseConfigResponse> responseList = new ArrayList<>();
        for (DatabaseConfig entity : result.getRecords()) {
            responseList.add(convertToResponse(entity));
        }
        responsePage.setRecords(responseList);
        
        return responsePage;
    }

    @Override
    public DatabaseConfigResponse getDatabaseConfigById(Long id) {
        DatabaseConfig entity = getById(id);
        if (entity == null) {
            throw new RuntimeException("数据库配置不存在");
        }
        
        return convertToResponse(entity);
    }

    @Override
    public Long create(DatabaseConfigRequest request) {
        DatabaseConfig entity = new DatabaseConfig();
        BeanUtil.copyProperties(request, entity);
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateTime(LocalDateTime.now());
        
        save(entity);
        return entity.getId();
    }

    @Override
    public void update(Long id, DatabaseConfigRequest request) {
        DatabaseConfig entity = getById(id);
        if (entity == null) {
            throw new RuntimeException("数据库配置不存在");
        }
        
        // 使用BeanUtil复制属性，保留原有的ID和创建时间
        BeanUtil.copyProperties(request, entity);
        entity.setUpdateTime(LocalDateTime.now());
        updateById(entity);
    }

    @Override
    public void delete(Long id) {
        removeById(id);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        DatabaseConfig entity = getById(id);
        if (entity != null) {
            entity.setUpdateTime(LocalDateTime.now());
            updateById(entity);
        }
    }

    @Override
    public List<DatabaseConfigResponse> getEnabledConfigs() {
        // 查询所有数据库配置（暂时不过滤状态，返回全部）
        List<DatabaseConfig> entities = list();
        
        List<DatabaseConfigResponse> responseList = new ArrayList<>();
        for (DatabaseConfig entity : entities) {
            DatabaseConfigResponse response = new DatabaseConfigResponse();
            BeanUtil.copyProperties(entity, response);
            responseList.add(response);
        }
        
        return responseList;
    }

    @Override
    public ConnectionTestResult testConnection(Long id) {
        DatabaseConfig dbConfig = getById(id);
        if (dbConfig == null) {
            throw new RuntimeException("数据库配置不存在");
        }
        return testConnectionInternal(dbConfig);
    }

    @Override
    public ConnectionTestResult testConnection(DatabaseConfigRequest request) {
        // 将请求转换为配置对象
        DatabaseConfig dbConfig = new DatabaseConfig();
        BeanUtil.copyProperties(request, dbConfig);
        return testConnectionInternal(dbConfig);
    }
    
    /**
     * 内部连接测试方法
     */
    private ConnectionTestResult testConnectionInternal(DatabaseConfig dbConfig) {
        ConnectionTestResult result = new ConnectionTestResult();
        long startTime = System.currentTimeMillis();
        
        try {
            // 测试连接并获取基本信息
            ConnectionInfo connectionInfo = databaseQueryService.testConnection(dbConfig);
            
            // 获取表数量
            Integer tableCount = databaseQueryService.getTableCount(dbConfig);
            
            long endTime = System.currentTimeMillis();
            
            result.setConnected(true);
            result.setLatency(endTime - startTime);
            result.setVersion(connectionInfo.getVersion());
            result.setTableCount(tableCount);
            
        } catch (Exception e) {
            result.setConnected(false);
            result.setErrorMessage("连接失败: " + e.getMessage());
            result.setLatency(System.currentTimeMillis() - startTime);
        }
        
        return result;
    }

    @Override
    public List<TableInfo> getTables(Long databaseId) {
        // 根据数据库配置ID获取数据库连接信息
        DatabaseConfig dbConfig = getById(databaseId);
        if (dbConfig == null) {
            throw new RuntimeException("数据库配置不存在");
        }
        
        return databaseQueryService.getTablesByDatabase(dbConfig);
    }

    @Override
    public TableStructure getTableStructure(Long databaseId, String tableName) {
        TableStructure structure = new TableStructure();
        structure.setTableName(tableName);
        structure.setTableComment("表注释");
        structure.setColumns(new ArrayList<>());
        return structure;
    }

    @Override
    public List<DbTypeStatistics> getDbTypeStatistics() {
        return new ArrayList<>();
    }
    
    /**
     * 转换实体为响应对象
     */
    private DatabaseConfigResponse convertToResponse(DatabaseConfig entity) {
        DatabaseConfigResponse response = new DatabaseConfigResponse();
        BeanUtil.copyProperties(entity, response);
        return response;
    }
}
